<template>
  <div>
    <a-card class="card" :bordered="false" :style="`min-height: ${cardMinHeight}px;`">

      <!--弹窗1详情-->
      <a-modal
          destroyOnClose
          class="detailModal"
          v-model='detailModal'
          width='1100px'
          :title="canBeQuery?'详情':title"
          @ok="submitDetail"
          @cancel="handleCancel1"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 100px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: center">
            <div style="width: 85%;">
              <a-form-model   layout="inline" ref="basicFormRef" >
                <a-form-model-item
                    required
                    label="计划单号"
                    prop="code"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="detailRecord.code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="编制人"
                    prop="code"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="detailRecord.create_user_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="编制日期"
                    prop="code"
                    style="margin-left: 42px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="detailRecord.create_time"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="状态"
                    prop="code"
                    style="margin-left: 43px">
                  <a-select
                      allowClear
                      :disabled="!canBeEdited || !isAdd"
                      show-search
                      style='width: 200px'
                      v-model.trim='detailRecord.status'
                      v-auth="`query`"
                  >
                    <a-select-option
                        v-for='item in planStatusList'
                        :key='item.code'
                        :value='item.code'
                    >{{item.description}}</a-select-option>
                  </a-select>
                </a-form-model-item>

              </a-form-model>


            </div>
          </div>
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;border-top: 1px solid #ddd;">
            <a-tabs type="card" :activeKey="tabKey" @change="callback" :tabBarGutter="tabBarGutter" :tabBarStyle="tabBarStyle" style="width: 100%;">
              <a-tab-pane key="1" tab="关联设备" :force-render="true">
                <div style="width: 100%;display: flex;flex-direction: row;">
                  <div style="width: 100%;">
                    <a-table
                        :columns="detail1Columns"
                        :data-source="detail1Data"
                        :pagination="detail1Pagination"
                        @change="onChangeDetail1"
                        :showPagination="true"
                        :loading="tableLoadingDetail1"
                        :rowKey="(record1) => {return record1.index}"
                        :scroll="{x:true,y: 165 }"
                    >
                      <template slot="action" slot-scope="recordPlan">
                        <a-popconfirm title="确定删除?" @confirm="() => delRelation(recordPlan)">
                          <a>删除</a>
                        </a-popconfirm>
                      </template>
                    </a-table>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-spin>
      </a-modal>


      <!--弹窗0 新增按钮-->
      <a-modal
          destroyOnClose
          class="addModal"
          v-model='addModal'
          width='1100px'
          :title="isAdd?'新增':title"
          @ok="submitAdd"
          @cancel="handleCancel0"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 30px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: space-between">
            <div style="width: 90%;">
              <a-form-model   layout="inline" ref="basicFormRef" >
                <a-form-model-item
                    label="保养类型"
                    style="margin-left: 0">
                  <a-select
                      show-search
                      allowClear
                      style='width: 150px'
                      @keydown.enter="addFilter"
                      @change="addFilter"
                      v-model.trim="addQueryForm.add_maintenance_type"
                      :disabled="!canBeEdited || !isAdd"
                  >
                    <a-select-option
                        v-for='item in deviceMaintenanceTypeList'
                        :key='item.id'
                        :value='item.id'
                    >{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>

                <a-form-model-item
                    label="设备组筛选"
                    style="margin-left: 0">
                  <a-select
                      show-search
                      allowClear
                      style='width: 250px'
                      @keydown.enter="addFilter"
                      @change="addFilter"
                      v-model.trim="addQueryForm.add_device_group"
                      :disabled="!canBeEdited || !isAdd"
                  >
                    <a-select-option
                        v-for='item in deviceGroupList'
                        :key='item.id'
                        :value='item.id'
                    >{{"编码:"+item.code+",名称:"+item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>

                <a-form-model-item
                    label="计划单号:">
                  <a-input style='width: 100px;height: 32px'  v-model.trim="addPlanCode" v-auth="`query`"></a-input>
                </a-form-model-item>

                <a-form-model-item>
                  <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="addReset" v-auth="`query`">
                    重置
                  </a-button>
                </a-form-model-item>

              </a-form-model>

            </div>
          </div>
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;border-top: 1px solid #ddd;">
            <a-table
                :columns="key1Columns"
                :data-source="addListFilter"
                :pagination="key1Pagination"
                @change="onChangeKey1"
                :showPagination="true"
                :loading="tableLoading01"
                :rowKey="(record1) => {return record1.index}"
                :scroll="{x:true,y: 300 }"
                style="width: 100%;"
            >
              <template slot="action0" slot-scope="record1">
                <a-input style='width: 80px;height: 32px'  v-model.trim="record1.add_expect_time" v-auth="`query`"></a-input>
              </template>
              <template slot="action" slot-scope="record1">
                <a-popconfirm title="确定删除?" @confirm="() => delOne(record1)">
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </a-table>
          </div>
        </a-spin>

      </a-modal>

      <page-head-area>
        <div class="extra" style="width: 260px;display: flex;justify-content: space-around">
<!--          <a-badge count="9">-->
            <a-button icon="plus-circle" v-auth="`insert`" @click="add" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">新增</a-button>
<!--          </a-badge>-->

          <a-popconfirm
              title="确定删除吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteMaintenancePlan"
          >
            <a-button icon="delete" v-auth="`delete`" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;"
            >删除</a-button>
          </a-popconfirm>
          <a-button icon="audit"  style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">审核</a-button>
          <a-button icon="download"  style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">导入</a-button>
        </div>
      </page-head-area>

      <div class="queryBox">
        <a-form-model layout="inline" :model='queryForm' ref="queryFormRef" class='query' style='display: flex;flex-wrap: wrap;'>

          <a-form-model-item
              label="状态"
              prop="status"
              style=""
              ref="statusRef"
          >
            <a-select
                allowClear
                show-search
                style='width: 150px'
                v-model.trim='queryForm.status'
                v-auth="`query`"
            >
              <a-select-option
                  v-for='item in planStatusList2'
                  :key='item.code'
                  :value='item.code'
              >{{item.description}}</a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
              label="日期范围"
              prop="date"
              ref="dateRef"
          >
            <a-range-picker
                :valueFormat="'YYYY-MM-DD'"
                :format="'YYYY-MM-DD'"
                v-model.trim="queryForm.dateSelect"
                allow-clear="true"/>
          </a-form-model-item>

          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="reset" v-auth="`query`">
              重置
            </a-button>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="filter" v-auth="`query`">
              搜索
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="dataBox">
        <a-table
            :columns="columns"
            :data-source="data"
            :pagination="false"
            :loading="tableLoading"
            :rowKey="(recordS) => {return recordS.id}"
            :scroll="{ x: 1000, y: 500 }"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="action" slot-scope="record">
              <a v-auth="`update`" @click="detail(record)">详情</a>
              <a-divider type="vertical"/>
              <a v-auth="`update`">编辑</a>
          </template>
        </a-table>

      </div>

      <a-pagination
          @change="onChangePage"
          @showSizeChange="showSizeChange"
          :total="pagination.total"
          :showSizeChanger="true"
          :showQuickJumper="true"
          :defaultPageSize="pagination.defaultPageSize"
          :pageSize="pagination.page_size"
          :pageSizeOptions="pagination.pageSizeOptions"
          :current="pagination.current"
          :showTotal="pagination.showTotal"
          style="width: 100%;display: flex;flex-direction: row;justify-content: flex-end;margin-top: 15px"
      ></a-pagination>
    </a-card>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import PageHeadArea from "../module/pageHeadArea.vue";
import axios from "axios";
import {
  deleteDeviceMaintenancePlan,
  deleteMaintenancePlanDeviceRelation,
  getDeviceGroupList, getDeviceGroupRelationList,
  getDeviceList,
  getDeviceMaintenancePlanList,
  getDeviceMaintenanceTypeList,
  getDeviceMaintenanceTypeProjectRelationList, getMaintenancePlanDeviceRelationList,
  getUserNameById, getWarningTimeList, saveDevice, saveDeviceMaintenancePlan, saveMaintenancePlanDeviceRelation
} from "../../utils/interface";
import {message} from "ant-design-vue";
import {get_device_maintenance_plan_list} from "../../services/deviceMaintenance";

const data = []
const columns = [
  { title: '计划单号', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '编制人', width: 120, align:'center',dataIndex: 'create_user_name', key: 'create_user_name'},
  { title: '编制日期', width: 120, align:'center',dataIndex: 'create_time', key: 'create_time'},
  { title: '状态', width: 120, align:'center',dataIndex: 'status_name', key: 'status_name'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

const key1Columns = [
  { title: '序号', width: 120, align:'center',dataIndex: 'id', key: 'id'},
  { title: '编码', width: 120, align:'center',dataIndex: 'add_device_code', key: 'add_device_code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'add_device_name', key: 'add_device_name'},
  { title: '保养日期', width: 120, align:'center',dataIndex: 'add_maintenance_date', key: 'add_maintenance_date'},
  { title: '保养类别', width: 120, align:'center',dataIndex: 'add_maintenance_type', key: 'add_maintenance_type'},
  { title: '状态', width: 120, align:'center',dataIndex: 'add_status_name', key: 'add_status_name'},
  { title: '预计用时(h)', width: 120, align:'center', scopedSlots: { customRender: 'action0' }},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }]

const detail1Columns = [
  { title: '设备名', width: 120, align:'center',dataIndex: 'device_name', key: 'device_name'},
  { title: '编码', width: 120, align:'center',dataIndex: 'device_code', key: 'device_code'},
  { title: '保养类型', width: 120, align:'center',dataIndex: 'maintenance_type_name', key: 'maintenance_type_name'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }
]

const detail2Columns = [
  { title: '保养单号', width: 120, align:'center',dataIndex: 'maintenanceId', key: 'maintenanceId'},
  { title: '日期', width: 120, align:'center',dataIndex: 'date', key: 'date'},
  { title: '保养人', width: 120, align:'center',dataIndex: 'person', key: 'person'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }
]

const detail3Columns = [
  { title: '点检单号', width: 120, align:'center',dataIndex: 'inspectionId', key: 'inspectionId'},
  { title: '日期', width: 120, align:'center',dataIndex: 'date', key: 'date'},
  { title: '点检人', width: 120, align:'center',dataIndex: 'person', key: 'person'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }
]

const detail4Columns = [
  { title: '维修单号', width: 120, align:'center',dataIndex: 'repairId', key: 'repairId'},
  { title: '日期', width: 120, align:'center',dataIndex: 'date', key: 'date'},
  { title: '维修人', width: 120, align:'center',dataIndex: 'person', key: 'person'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }
]

const detail5Columns = [
  { title: '编码', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'name', key: 'name'},
  { title: '规格', width: 120, align:'center',dataIndex: 'specification', key: 'specification'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }
]

const key1Data =[  {
  serialNumber: 1,
  id: 'A001',
  name: '设备A',
  maintenanceDate: '2023-10-01',
  type: '常规保养',
  status: '已完成',
  estimatedTime: '2小时'
},
  {
    serialNumber: 2,
    id: 'B002',
    name: '设备B',
    maintenanceDate: '2023-10-02',
    type: '预防性保养',
    status: '进行中',
    estimatedTime: '3小时'
  }];

const detail1Data = [
  { id: 1, name: '产品A', specification: '规格A', quantity: 100 },
  { id: 2, name: '产品B', specification: '规格B', quantity: 200 },
  { id: 3, name: '产品C', specification: '规格C', quantity: 150 },
  { id: 4, name: '产品D', specification: '规格D', quantity: 300 },]

const detail2Data = [
  { maintenanceId: 'M001', date: '2022-01-01', person: '张三' },
  { maintenanceId: 'M002', date: '2022-01-02', person: '李四' },
  { maintenanceId: 'M003', date: '2022-01-03', person: '王五' },
  { maintenanceId: 'M004', date: '2022-01-04', person: '赵六' },]

const detail3Data = [
    { inspectionId: 'I001', date: '2022-01-01', person: '张三' },
  { inspectionId: 'I002', date: '2022-01-02', person: '李四' },
  { inspectionId: 'I003', date: '2022-01-03', person: '王五' },
  { inspectionId: 'I004', date: '2022-01-04', person: '赵六' },]

const detail4Data = [
  { repairId: 'R001', date: '2022-01-01', person: '张三' },
  { repairId: 'R002', date: '2022-01-02', person: '李四' },
  { repairId: 'R003', date: '2022-01-03', person: '王五' },
  { repairId: 'R004', date: '2022-01-04', person: '赵六' },
]

const detail5Data = [
  { code: 'A001', name: '产品A', specification: '规格A' },
  { code: 'A002', name: '产品B', specification: '规格B' },
  { code: 'A003', name: '产品C', specification: '规格C' },
  { code: 'A004', name: '产品D', specification: '规格D' },
]
export default {
  name: "userAuthority",
  components: {PageHeadArea},
  data() {
    return {
      selectedRowKeys: [],
      tableLoadingDetail1:false,
      detailRecord:{},
      addPlanCode:'',
      warningTime:undefined,
      deviceGroupList:[],
      addListFilter:[],
      deviceMaintenanceTypeList:[], //设备保养类型
      planStatusList2:[
        {code:null,description: '不限'},
        { code: 0, description: "计划中" },
        { code: 1, description: "计划完成" },
        { code: 2, description: "视情况而定" }],
      planStatusList:[
        { code: 0, description: "计划中" },
        { code: 1, description: "计划完成" },
        { code: 2, description: "视情况而定" }],
      basicForm:{
        code: '',
        create_time: '',
        create_user: '',
        id: '',
        status: '',
      },
      key1Data,
      key1Columns,
      detail1Columns,
      detail1Data,
      detail2Columns,
      detail2Data,
      detail3Columns,
      detail3Data,
      detail4Columns,
      detail4Data,
      detail5Columns,
      detail5Data,
      tableLoading01: false,
      axiosSource: null,
      tabKey: '1',
      title:'',
      tabBarGutter: 0,
      tabBarStyle: {
        color: 'rgba(0, 0, 0, 0.85)'
      },
      bodyStyle: {
        'padding': '0px 24px 0px 24px',
        'font-size': '14px',
        'line-height': '1.5',
        'word-wrap': 'break-word',
      },
      cardMinHeight: 0,
      queryForm: {
        status: undefined,
        dateSelect: [],
      },
      addQueryForm:{
        add_maintenance_type: undefined,
        add_device_group: undefined,
      },
      statusList: [
        // {id: 1, name: '待采购', code: '0', type: 'use_status'},
        {id: 1, name: '正常运行', code: '1',type: 'use_status'},
        {id: 2, name: '不正常运行', code: '2',type: 'use_status'},
      ],
      data,
      columns,
      pagination: {
        total: 0,
        page_size: 10,
        defaultPageSize: 10,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '50', '100', '500'],
      },
      tableLoading: false,
      addModal: false,
      canBeEdited: false, //是否可编辑
      isAdd: false, //是否为新增
      spinning: false,

      detailModal:false, //详情弹窗
      canBeQuery:false, //是否可查询

      remodelModal:false,
      disposalModal:false,
      maintenance_detailsModal:false,
      key1Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      detail1Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      detail2Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      detail3Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      detail4Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      detail5Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
    }
  },
  watch: {},
  authorize: {
    add: 'insert',
    getAssetLedgerList: 'query',
    reset: 'query',
    query: 'query',
    detail: 'query',
    edit: 'update',
    del: 'delete',
    check: 'check',
  },
  computed: {
    ...mapGetters(['getCardMinHeight']),
  },
  created() {
    this.cardMinHeight = this.getCardMinHeight
  },
  async mounted() {
    this.axiosSource = axios.CancelToken.source();

    //设备组
    this.deviceGroupList = await getDeviceGroupList()

    //预警时间
    await getWarningTimeList().then(res => {
      if(res.length===0){
        message.error('请先设置预警时间')
        return
      }
      this.warningTime=res[0]?.time || ''
    })

    await getDeviceMaintenanceTypeList().then(res => {
      this.deviceMaintenanceTypeList = res
    })
    await this.initialize()
  },
  methods: {
    onChangePage (page, pageSize) {
      this.pagination.current = page
      this.pagination.page_size = pageSize
      this.pagination.page = page
      this.initialize()
    },
    showSizeChange(current, size){
      this.pagination.page_size = size
      this.pagination.current = current
      this.pagination.page = current
      this.initialize()
    },
    calculateAddMaintenanceDate(lastMaintenanceTime, maintenanceCycle) {
      // 创建一个 Date 对象，表示 last_maintenance_time
      let date = new Date(lastMaintenanceTime);
      // 添加 maintenance_cycle 小时
      date.setHours(date.getHours() + maintenanceCycle);
      // 返回格式化后的日期
      return date.toISOString().replace('T', ' ').replace(/\.\d+Z$/, '');
    },
    addFilter(){
      //筛选
      this.key1Pagination.page=1
      this.key1Pagination.current=1
      this.key1Pagination.page_size=4
      //筛选
      this.addListFilter = this.key1Data.filter(item => {
        // 检查每个条件是否满足
        return (
            (this.addQueryForm.add_maintenance_type !== undefined ? item.maintenance_type_id === this.addQueryForm.add_maintenance_type : true) &&
            (this.addQueryForm.add_device_group !== undefined ? item.add_device_group === this.addQueryForm.add_device_group : true)
        );
      })
    },

    delOne(record){
      //逻辑删除
      this.addListFilter = this.addListFilter.filter(it => it !== record);

    },
    async filter() {
      //筛选
      this.pagination.page = 1
      this.pagination.current = 1
      this.pagination.page_size = 10
      this.tableLoading = true
      await this.initialize()

      this.tableLoading = false;
    },
    async initialize() {
      //数据初始化
      this.tableLoading=true

      const paramsAll = Object.assign({}, {}, {
        "page": this.pagination.page,
        "page_size": this.pagination.page_size
      });
      await get_device_maintenance_plan_list(paramsAll).then(async res => {
        this.data=[]
        if(res.data.code !== '1000'){
          this.tableLoading =false
        }else {
          this.pagination.total = res.data.extension.total+(this.pagination.current-1)*this.pagination.page_size
          for (const item of res.data.data) {
            if(item.create_user!==null){
              item['create_user_name'] = await getUserNameById(item.create_user)
            }else {
              item['create_user_name']=''
            }

            item['status_name'] = this.planStatusList.find(it => it.code === item.status)?.description || ''

          }
          //
          const [startDate, endDate] = this.queryForm.dateSelect;
          this.data = res.data.data.filter(item => {
            // 检查每个条件是否满足
            return (
                (this.queryForm.status !== undefined ? item.status === this.queryForm.status : true) &&
                (startDate ? new Date(item.create_time) >= new Date(startDate) : true) &&
                (endDate ? new Date(item.create_time) <= new Date(endDate) : true)
            );
          });
        }
      })
      this.tableLoading=false
    },
    onChangeDate(date, dateString) {
      console.log(date, dateString);
    },
    callback (key) { // assetCode
      this.tabKey = key
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    statusChange() {
      console.log(this.queryForm.mask_status);
    },
    // 分页切换
    onChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.page_size = pagination.pageSize
      this.pagination.page = pagination.current
      this.getAssetLedgerList()
    },
    // 分页切换
    onChangeKey1 (pagination) {
      this.key1Pagination.current = pagination.current
      this.key1Pagination.page_size = pagination.pageSize
      this.key1Pagination.page = pagination.current
    },
    onChangeDetail1(pagination) {
      this.detail1Pagination.current = pagination.current
      this.detail1Pagination.page_size = pagination.pageSize
      this.detail1Pagination.page = pagination.current
    },
    onChangeDetail2(pagination) {
      this.detail2Pagination.current = pagination.current
      this.detail2Pagination.page_size = pagination.pageSize
      this.detail2Pagination.page = pagination.current
    },
    onChangeDetail3(pagination) {
      this.detail3Pagination.current = pagination.current
      this.detail3Pagination.page_size = pagination.pageSize
      this.detail3Pagination.page = pagination.current
    },
    onChangeDetail4(pagination) {
      this.detail4Pagination.current = pagination.current
      this.detail4Pagination.page_size = pagination.pageSize
      this.detail4Pagination.page = pagination.current
    },
    onChangeDetail5(pagination) {
      this.detail5Pagination.current = pagination.current
      this.detail5Pagination.page_size = pagination.pageSize
      this.detail5Pagination.page = pagination.current
    },
    async query() {
      this.pagination.page = 1
      this.pagination.current = 0
      this.pagination.page_size = 10
      await this.initialize()
    },
    addReset(){

      this.tableLoading01=true
      this.addListFilter=[]
      this.addQueryForm={
        add_maintenance_type: undefined,
        add_device_group: undefined,
      }
      this.addListFilter = this.key1Data
      this.tableLoading01=false
    },
    reset() {
      this.queryForm = {
        status: undefined,
        dateSelect: [],

      }
      this.query()
    },
    async deleteMaintenancePlan() {
      for (const it of this.selectedRowKeys) {
        await deleteDeviceMaintenancePlan({'id': it})
      }
      message.success('删除成功')
      //重新加载
      await this.initialize()
    },
    submitDetail(){
      // console.log(this.detailRecord)
      // saveDeviceMaintenancePlan({'id':this.detailRecord.id,'code':this.detailRecord.code,'status':this.detailRecord.status})
      message.success('修改成功')
      // this.initialize()
      this.handleCancel1()
    },
    async delRelation(record) {
      // console.log(record)
      //删除联系
      await deleteMaintenancePlanDeviceRelation({'id': record.id}).then(async res => {
        //重刷
        this.detail1Data = []
        this.tableLoadingDetail1 = true
        await getMaintenancePlanDeviceRelationList({'plan_id': this.detailRecord.id}).then(async res => {
          if (res === 'NoData' || res === 'Error') {
            this.detail1Data = []
            this.tableLoadingDetail1 = false;
          } else {
            for (const it of res) {
              let result = await getDeviceList({'device_id': it.device_id})
              it['device_id'] = result[0]?.id || ''
              it['device_code'] = result[0]?.code || ''
              it['device_name'] = result[0]?.name || ''
              it['maintenance_type_name'] = this.deviceMaintenanceTypeList.find(it2 => it2.id === it.maintenance_type_id).name

              this.detail1Data.push(it)
            }
          }

        })
      }).then(res => {
        message.success('删除成功')
      })


    },
    async add() {
      this.addListFilter = []
      this.key1Data=[]
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
      this.tableLoading01= true
      await getDeviceMaintenanceTypeProjectRelationList().then(async res => {
        if(res.length===0){
          this.tableLoading01 =false
          this.addListFilter = []
          this.key1Data=[]
        }
        else{
          if(this.warningTime===undefined){
            message.error('请先设置预警时间')
            return
          }
          for (const item of res) {
            if(item.status===0){
              item['add_maintenance_type'] =this.deviceMaintenanceTypeList.find(it=>it.id === item.maintenance_type_id)?.name || ''
              item['add_status_name'] = this.planStatusList.find(it=>it.code === item.status)?.description || ''
              await getDeviceList({'id':item.device_id}).then(res2=>{
                item['add_device_code'] = res2[0]?.code || ''
                item['add_device_name'] = res2[0]?.name || ''
                // item['add_maintenance_date'] = res2[0].last_maintenance_time+res2[0].maintenance_cycle
                //无记录
                if(res2[0].last_maintenance_time===null || res2[0].last_maintenance_time===undefined){
                  res2[0].last_maintenance_time=res2[0].create_time
                }
                item['add_maintenance_date'] = this.calculateAddMaintenanceDate(res2[0].last_maintenance_time, res2[0].maintenance_cycle);
                item['last_maintenance_time']= res2[0]?.last_maintenance_time || ''
              })
              //设备组
              await getDeviceGroupRelationList({'device_id':item.device_id}).then(res3=>{
                item['add_device_group'] =res3[0]?.group_id || '';
              })

              if(this.isAfterNow(item.add_maintenance_date, this.warningTime)&&this.isBeforeToday(item['last_maintenance_time'])){
                item['add_expect_time']=undefined
                this.addListFilter.push(item)
                this.key1Data.push(item)
              }
            }
          }
        }


      })
      this.tableLoading01= false
    // console.log("this.addListFilter",this.addListFilter)
    },
    async submitAdd() {
      if (this.addPlanCode === '') {
        message.error('请填写计划单号号')

      } else {

        let flag = true
        this.addListFilter.forEach(it => {
          if (it.add_expect_time === undefined || it.add_expect_time === '') {
            flag = false
          }
        })
        if (flag === false) {
          message.error('请填写预计完成时间')
          return
        }
          //新增计划
          //查重
          let searchCodeList = await getDeviceMaintenancePlanList({'code': this.addPlanCode})
          if (searchCodeList.length > 0) {
            for(const searchItem of searchCodeList){
              if(searchItem.code===this.addPlanCode){
                flag = false
                break
              }
            }
          }
          if(flag===false){
            message.error('计划单号已存在')
            return
          }
          let plan_id = undefined
          await saveDeviceMaintenancePlan({'code':this.addPlanCode,'status':0}).then(async res2 => {
            //拿plan_id
              await getDeviceMaintenancePlanList({'code': this.addPlanCode}).then(res3=>{
                for(const searchCodeItem of res3){
                  if(searchCodeItem.code===this.addPlanCode){
                    plan_id=searchCodeItem.id
                    break
                  }
                }
              })

          })
          //添加relation
          for (const item of this.addListFilter) {
            console.log({'plan_id':plan_id,'device_id':item.device_id,'maintenance_type_id':item.maintenance_type_id,'expect_time':item.add_expect_time})
            await saveMaintenancePlanDeviceRelation({
              'plan_id': plan_id,
              'device_id': item.device_id,
              'maintenance_type_id': item.maintenance_type_id,
              'expect_time': item.add_expect_time,
              'maintenance_time': item.add_maintenance_date

            })
            //改device表
            let deviceSearch = await getDeviceList({'id':item.device_id})
            let add_maintenance_date = this.calculateAddMaintenanceDate(deviceSearch[0].last_maintenance_time, deviceSearch[0].maintenance_cycle);
            await saveDevice({'id':item.device_id,'last_maintenance_time':add_maintenance_date})
          }
          this.handleCancel0()
          message.success('添加成功')
          this.addPlanCode=''
          //重新加载
          await this.initialize()
      }

    },
    isAfterNow(addMaintenanceDate, warningTime) {
      let result = this.calculateAddMaintenanceDate(addMaintenanceDate, warningTime)
      // 获取当前时间
      let now = new Date();
      let date = new Date(result);

      // 比较日期
      return date > now;
    },
    edit(record) {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = false
      this.echo(record)
    },
    async detail(record) {
      this.detail1Data=[]
      this.detailModal = true
      this.canBeEdited = false
      this.canBeQuery = true
      this.isAdd = true
      this.tableLoadingDetail1= true
      await this.echo(record)
      //拿关联device
      await getMaintenancePlanDeviceRelationList({'plan_id':this.detailRecord.id}).then(async res => {
        if(res.length===0){
          this.detail1Data = []
          this.tableLoadingDetail1=false;
        }else{
          for (const it of res) {
            let result = await getDeviceList({'device_id': it.device_id})
            it['device_id']=result[0]?.id || ''
            it['device_code']=result[0]?.code || ''
            it['device_name']=result[0]?.name || ''
            it['maintenance_type_name']= this.deviceMaintenanceTypeList.find(it2=>it2.id === it.maintenance_type_id).name

            this.detail1Data.push(it)
          }
        }

      })
      this.tableLoadingDetail1= false
    },
    isBeforeToday(item) {
      // 获取当前时间
      const now = new Date();

      // 获取item['last_maintenance_time']的日期部分
      const lastMaintenanceTime = new Date(item);

      // 比较日期部分
      return lastMaintenanceTime < now;
    },
    echo(record){
      this.detailRecord= record
    },
    clearParameter() {},
    handleCancel() {
      this.tabKey = '1'
      console.log("tabkey",this.tabKey);
    },
    handleCancel0() {
      this.addModal = false
      this.canBeEdited = false
      this.isAdd = false
      this.key1Data.forEach(item=>{item.add_expect_time=undefined})
    },
    handleCancel1(){
      this.detailModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    handleCancel2(){
      this.disposalModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    submit() {

    },

  },
  beforeDestroy() {
    if (this.axiosSource) {
      this.axiosSource.cancel('Request canceled due to page navigation.');
    }
  }
}
</script>

<style scoped lang="less">

.dataBox{
  margin-top: 20px;
}

.hide-scrollbar::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}
.hide-scrollbar {
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
  overflow-y: scroll; /* 保持内容可滚动 */
}
.demo-infinite-container {
  margin-top: 0px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 300px;
}
/deep/ .ant-form-inline .ant-form-item-with-help{
  margin-bottom: 0px;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #f5f5f5;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .unit .ant-select-selection--single{
  margin-left: 0px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: 0;
}
/deep/ .ant-select-disabled .ant-select-selection {
  background-color: #fff;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .ant-input-number-disabled{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
</style>